package org.adorsys.aderp.aderplogin.client.common;

import org.adorsys.aderp.aderplogin.client.OauthTokenUserDetailsServiceWrapper;
import org.adorsys.aderp.aderplogin.client.hessian.HessianUserDetailsServiceWrapper;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.security.core.userdetails.AuthenticationUserDetailsService;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken;

/**
 * This bean is in charge of populating the user detail object with 
 * credentials required to run this app. 
 * 
 * In particular the user name that is required by the application for 
 * login.
 * 
 * It will contact the login application that maps oauth token to
 * a user permission profile and return that permission profile in form of a user detail.
 * 
 * @author francis
 *
 * @param <T>
 */
public class RoutingUserDetailsServiceWrapper implements
		AuthenticationUserDetailsService<PreAuthenticatedAuthenticationToken>, InitializingBean {

	HessianUserDetailsServiceWrapper hessian;
	OauthTokenUserDetailsServiceWrapper oauth;
	
	@Override
	public UserDetails loadUserDetails(PreAuthenticatedAuthenticationToken token)
			throws UsernameNotFoundException {
		Object object = token.getPrincipal();
		if(object instanceof Oauth2User){
			return hessian.loadUserDetails(token);
		} else if (object instanceof OAuth2AccessToken){
			return oauth.loadUserDetails(token);
		} else {
			throw new IllegalStateException("Unsupported user detial service wrapper.");
		}
	}

	public void setHessian(HessianUserDetailsServiceWrapper hessian) {
		this.hessian = hessian;
	}

	public void setOauth(OauthTokenUserDetailsServiceWrapper oauth) {
		this.oauth = oauth;
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		if(hessian==null) throw new IllegalStateException("Dependency to HessianUserDetailsServiceWrapper missing");
		if(oauth==null) throw new IllegalStateException("Dependency to OauthTokenUserDetailsServiceWrapper missing");
	}
	

}
